<template>
  <!-- <div class="layout"> -->
    <!-- <div class="main-box"> -->
      <h3 style="margin: 10px 20px 0;">销售订单</h3>
      <div class="search-box">
        <el-form :model="searchInfo" label-position="top">
        <div class="flex-container">
          <el-form-item label="客户名称">
            <el-input 
              v-model="searchInfo.clientName"
              style="width: 220px;"
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><search /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="商品名称">
            <el-input 
              v-model="searchInfo.skuName"
              style="width: 220px;"
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><search /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="规格型号">
            <el-input 
              v-model="searchInfo.spec[searchInfo.spec.selected]"
              style="width: 220px;"
              @input="handleSearch"
            >
              <template #prepend>
                <el-select v-model="searchInfo.spec.selected" style="width: 100px"
                  @change="handleSpecSelect"
                >
                  <el-option label="长" value="length" />
                  <el-option label="宽" value="width" />
                  <el-option label="厚" value="thickness" />
                  <el-option label="直/外径" value="diameter" />
                  <el-option label="内径" value="innerD" />
                  <el-option label="其他" value="otherSpec" />
                </el-select>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="下单日期">
            <div style="width: 220px;">
              <el-date-picker
                style="width: 100%;"
                v-model="searchInfo.orderDt"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                size="default"
                value-format="YYYY-MM-DD"
                @change="getTableData"
              />
            </div>
          </el-form-item>
          <el-form-item label="要求送达日期">
            <div style="width: 220px;">
              <el-date-picker
                style="width: 100%;"
                v-model="searchInfo.scheduledDt"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                size="default"
                value-format="YYYY-MM-DD"
                @change="getTableData"
              />
            </div>
          </el-form-item>
        </div>
        </el-form>
      </div>
      <div class="btn-list">
        <div class="left-btns">
          <el-button 
            type="primary" 
            icon="plus" 
            style="width: 100px;margin-right: 6px;"
            @click="handleAdd"
          >
            添加
          </el-button>
          <el-button
            icon="delete" text
            :disabled="!orderIds.length"
            @click="handleDelete"
          >
            删除
          </el-button>
          <el-button 
            icon="upload" text
            @click="handleExport"
          >
            导出
          </el-button>
          <el-button 
            icon="clock" text
            @click="handleLog"
          >
            历史记录
          </el-button>
          <el-button 
            icon="refresh" text
            @click="getTableData"
          >
            刷新
          </el-button>
          <el-button 
            icon="refresh" text
            @click="handleReset"
          >
            重置
          </el-button>
          <el-button
            @click="handleShowQrCode"
            icon="ChatDotRound" text
          >
            微信服务号
          </el-button>
        </div>
      </div>
      <div class="table-box">
        <el-table 
          ref="orderTableRef"
          :data="orderStore.orderList"
          style="width: 100%; height: 100%;"
          :span-method="objectSpanMethod"
          @cell-mouse-enter="handleCellMouseEnter"
          @cell-mouse-leave="handleCellMouseLeave"
          :row-class-name="tableRowClassName"
          @selection-change="handleSelectionChange"
          @sort-change="handleSortChange"
          :cell-style="tableCellStyle"
          :header-cell-style="{ textAlign: 'center' }" 
          v-loading="loading"
          element-loading-text="订单数据加载中..."
          border
        >
          <el-table-column prop="selection" type="selection" width="40" />
          <el-table-column sortable="custom" prop="clientName" label="客户" width="120" fixed />
          <el-table-column sortable="custom" prop="skuName" label="商品名称" width="120" />
          <el-table-column sortable="custom" prop="skuBrand" label="商品牌号" width="100" />
          <el-table-column sortable="custom" prop="internalBrand" label="内部牌号" width="100" />
          <el-table-column sortable="custom" prop="specification" label="规格型号" width="140" />
          <el-table-column sortable="custom" prop="orderState" label="订单状态" width="100">
            <template #default="scope">
              <el-tag
                :type="handleOrderState(scope.row.orderState)"
              >
                {{ scope.row.orderState }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column sortable="custom" prop="unitPrice" label="单价" width="80" />
          <el-table-column sortable="custom" prop="amount" label="金额" width="100">
            <template #default="scope">
              <span :style="{color: scope.row.isEstimate === 1 ? '#f5222d' : '' }">
                {{ scope.row.amount }}
              </span>
            </template>
          </el-table-column>
          <el-table-column sortable="custom" prop="quantity" label="订单量" width="90" />
          <el-table-column sortable="custom" prop="unit" label="订货单位" width="90" />
          <el-table-column sortable="custom" prop="byQuantity" label="按数量" width="80" >
            <template #default="scope">
              <span>{{ scope.row.byQuantity === "1" ? "是" : "否" }}</span>
            </template>
          </el-table-column>
          <el-table-column sortable="custom" prop="weight" label="订货重量" width="100">
            <template #default="scope">
              <span :style="{color: scope.row.isEstimate === 1 ? '#f5222d' : '' }">
                {{ scope.row.weight ?? "N/A" }}
              </span>
            </template>
          </el-table-column>
          <el-table-column sortable="custom" prop="actualDeliver" label="实送" width="90"/>
          <el-table-column sortable="custom" prop="oweDeliver" label="欠送" width="90" />
          <el-table-column sortable="custom" prop="orderDt" label="下单日期" width="120"/>
          <el-table-column sortable="custom" prop="scheduledDt" label="要求送达日期" width="130"/>
          <el-table-column sortable="custom" prop="completeDt" label="订单完成日期" width="130"/>
          <!-- <el-table-column prop="clientCode" label="客户代号" width="100" /> -->
          <el-table-column sortable="custom" prop="orderId" label="订单号" width="130" show-overflow-tooltip />
          <el-table-column prop="remark" label="备注" width="130" show-overflow-tooltip />
          <el-table-column prop="operation" label="操作" width="80" fixed="right" align="center">
            <template #default="scope">
              <el-button type="primary" plain size="small" @click="handleEdit(scope?.row)">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination-box">
          <el-pagination 
            layout="sizes, prev, pager, next" 
            :total="total"
            v-model:current-page="pageNum"
            v-model:page-size="pageSize"
            :page-sizes="[5, 10, 30, 50]"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
          />
      </div>
      <logDialog v-model="logVisible" ref="logRef" logType="订单管理" />
      <orderDialog v-model="dialogVisible" :dialogType="dialogType" :getTableData="getTableData"/>
    <!-- </div> -->
  <!-- </div> -->
</template>

<script setup lang="ts">
import { ref, nextTick, watchEffect, onMounted, h } from 'vue'
import orderDialog from '@/pages/home/views/sale/order/components/orderDialog.vue'
import logDialog from '@/pages/home/views/sale/order/components/logDialog.vue'
import { useOrderStore } from '@/stores/sale/order'
import { getOrderList, deleteOrder, exportOrders } from '@/pages/home/views/sale/api/order'
import { dragTable } from '@/pages/home/views/sale/utils/dragTable'
import * as CONFIG from '@/pages/home/views/sale/config/order'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getWeChatQrCode, getAllSpecifications } from '@/pages/home/views/sale/api/other'

const orderStore = useOrderStore()
const dialogVisible = ref(false)
const logVisible = ref(false)
const dialogType = ref('view')
const currentOrder = ref('')
const searchInfo = ref({
  clientName: "",
  skuName: "",
  orderDt: "",
  scheduledDt: "",
  spec: {
    selected: "length",
    length: "",
    width: "",
    thickness: "",
    diameter: "",
    innerD: "",
    otherSpec: ""
  },
  fieldName4Sort: null,
  sortType: null
})
const pageNum = ref(1)
const pageSize = ref(30)
const total = ref(0)
const orderIds = ref([])
const logRef = ref()
const orderTableRef = ref()
const loading = ref(true)

const tableCellStyle = ref({
    background: 'var(--el-table-tr-bg-color)',
    textAlign: 'center',
})

const handleSpecSelect = () => {
  searchInfo.value.spec.length = ""
  searchInfo.value.spec.width = ""
  searchInfo.value.spec.thickness = ""
  searchInfo.value.spec.diameter = ""
  searchInfo.value.spec.innerD = ""
  searchInfo.value.spec.otherSpec = ""
}
const handleCellMouseEnter = (row, column, cell, event) => {
  currentOrder.value = row.orderId
}
const handleCellMouseLeave = () => {
  currentOrder.value = ""
}
const tableRowClassName = ({
  row,
  rowIndex,
}) => {
  if (row.orderId === currentOrder.value) {
    return 'hovering-row'
  }
  return "";
}
const handleEdit = async (row) => {
  dialogType.value = 'edit'
  handleVisable(true)
  console.log("order init", JSON.parse(JSON.stringify(orderStore.order)))
  await nextTick()
  orderStore.editOrder(orderStore.orderData.find((item) => item.orderId === row.orderId))
  console.log("order value", JSON.parse(JSON.stringify(orderStore.order)))
}
const handleAdd = async () => {
  dialogType.value = 'add'
  console.log("order init", JSON.parse(JSON.stringify(orderStore.order)))
  handleVisable(true)

  const specs = await getAllSpecifications()
  orderStore.allSpecification = specs.data.data
}
const handleSearch = debounce(async () => {
  await getTableData()
}, 500)
const handleReset = async () => {
  searchInfo.value = {
    clientName: "",
    skuName: "",
    orderDt: "",
    scheduledDt: "",
    spec: {
      selected: "length",
      length: "",
      width: "",
      thickness: "",
      diameter: "",
      innerD: "",
      otherSpec: ""
    },
    fieldName4Sort: null,
    sortType: null
  }
  await getTableData()
}
const handleVisable = (val) => {
  dialogVisible.value = val
}
const handleLogVisable = (val) => {
  logVisible.value = val
}
const objectSpanMethod = ({
  row,
  column,
  rowIndex,
  columnIndex,
}) => {
  if (["selection", "clientName", "orderDt", "scheduledDt", "orderId", "operation", "remark"].includes(column.property)) {
    if (rowIndex > 0 && orderStore.orderList[rowIndex]["orderId"] === orderStore.orderList[rowIndex - 1]["orderId"]) {
      return {
        rowspan: 0,
        colspan: 0,
      }
    }
    return {
      rowspan: getRowspan("orderId", rowIndex),
      colspan: 1,
    }
  }
}
const getRowspan = (key, rowIndex) => {
  let rowspan = 1;
  let curVal = orderStore.orderList[rowIndex][key];
  for (let i = rowIndex + 1; i < orderStore.orderList.length; i++) {
    if (orderStore.orderList[i][key] === curVal) {
      rowspan++;
    }
    else break
  }
  return rowspan;
}

const handleSelectionChange = (rows) => {
  orderIds.value = rows.map(row => row.orderId)
}

const handleDelete = async () => {
    let ids = orderIds.value.join(",")
    const res = await deleteOrder({ orderIds: ids })
    console.log("delete res:", res.data)
    getTableData()
}

const handleExport = async () => {
    const res = await exportOrders({
      clientName: searchInfo.value.clientName,
      skuName: searchInfo.value.skuName,
      orderDtFrom: searchInfo.value.orderDt?.[0],
      orderDtTo: searchInfo.value.orderDt?.[1],
      scheduledDtFrom: searchInfo.value.scheduledDt?.[0],
      scheduledDtTo: searchInfo.value.scheduledDt?.[1],
      pageNum: pageNum.value,
      pageSize: pageSize.value
    })
    // console.log("res.data:", res.data)
    // console.log("res.data instanceof Blob:", res.data instanceof Blob)
    const blob = new Blob(
      [res.data],
      { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }
    )
    const url = URL.createObjectURL(blob)
    const a = document.createElement("a")
    a.href = url
    a.download = "销售订单.xlsx"
    a.click()
    URL.revokeObjectURL(url)
}

const handleLog = async () => {
  handleLogVisable(true)
  await logRef.value.getLogTableData()
}

const handleCurrentChange = (val) => {
    pageNum.value = val
    getTableData()
}

const handleSizeChange = (val) => {
    pageSize.value = val
    getTableData()
}

const handleOrderState = (row) => {
  switch (row) {
    case "已完成":
      return "success"
    case "部分送货":
      return "warning"
    case "送货审核":
      return "warning"
    case "待送货":
      return "danger"
    default:
      return "info"
  }
}

const handleSortChange = ({column, prop, order }) => {
  searchInfo.value.fieldName4Sort = CONFIG.ORDER_SORT_DB[prop]
  searchInfo.value.sortType = order === "ascending" ? "asc" : order === "descending" ? "desc" : null
  getTableData()
}

const handleShowQrCode = async () => {
  try {
    const QrCode = await getWeChatQrCode()
    const imgSrc = QrCode?.data
    await ElMessageBox(
      {
        message: 
          h('img', 
            { 
              src: imgSrc,
              style: 'width: 300px; height: 300px;',
              alt: '微信服务号二维码图片'
            }
          ),
        center: true,
        showConfirmButton: false,
        customStyle: { width: '320px', height: '320px' }
      }
    )
  }
  catch(error) { 
    error !== 'cancel' && ElMessage.error(error)
  }
}

function debounce (func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const context = this
        const later = () => {
            func.apply(context, args)
        };
        clearTimeout(timeout)
        timeout = setTimeout(later, wait)
    };
}

const getTableData = async () => {
  loading.value = true
  try {
    const orderData = await getOrderList({
      clientName: searchInfo.value.clientName,
      skuName: searchInfo.value.skuName,
      orderDtFrom: searchInfo.value.orderDt?.[0] ?? "",
      orderDtTo: searchInfo.value.orderDt?.[1] ?? "",
      scheduledDtFrom: searchInfo.value.scheduledDt?.[0] ?? "",
      scheduledDtTo: searchInfo.value.scheduledDt?.[1] ?? "",
      spec: {
        length: searchInfo.value.spec.length,
        width: searchInfo.value.spec.width,
        thickness: searchInfo.value.spec.thickness,
        diameter: searchInfo.value.spec.diameter,
        innerD: searchInfo.value.spec.innerD,
        otherSpec: searchInfo.value.spec.otherSpec
      },
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      fieldName4Sort: searchInfo.value.fieldName4Sort,
      sort: searchInfo.value.sortType
    })
    if(orderData.data.success === false) {
      throw new Error(orderData.data.errorMsg)
    }
    orderStore.orderData = orderData.data.data.list
    total.value = orderData.data.data.total
    orderStore.getOrderList()
    console.log("orderData:", orderData.data)
    loading.value = false
  }
  catch (error) {
    ElMessage.error(error.message || "调用接口异常")
    loading.value = false
  }
}

onMounted(() => {
  // console.log("orderTableRef", orderTableRef.value)
  dragTable(orderTableRef)
  getTableData()
})


</script>

<style scoped>
.search-box {
  margin: 10px 20px;
}
.flex-container {
  display: flex;
  flex-flow: row wrap;
  gap: 12px;
  align-items: flex-end;
}
.table-box{
    flex: 1;
    overflow-y: auto;
    margin: 0 20px;
    border: none;
}
.pagination-box {
    margin: 10px 20px;
    display: flex;
    justify-content: flex-end;
}
.btn-list {
    border: 1px solid #e1e3e5;
    border-bottom: none;
    border-radius: 4px 4px 0 0;
    margin: 0 20px;
    padding: 6px 12px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    overflow: hidden;
}
.left-btns {
    display: flex;
    align-items: center;
}
.right-btns {
    width: 300px;
    display: flex;
    align-items: center;
    justify-content: space-between;
}
.el-form-item {
  margin-bottom: 0;
}
.el-button.is-text {
  padding: 0 6px;
  margin: 0;
}
.el-table {
    --el-table-header-bg-color: var(--el-bg-color-page);
    --el-table-border-color: var(--el-border-color-dark);
    --el-table-header-text-color: var(--el-text-color-primary);
}
:deep(.el-table .hovering-row) {
  --el-table-tr-bg-color: #f5f7fa;
}

:deep(th.el-table__cell){
  border-bottom: var(--el-table-border) !important;
}
:deep(.el-table-fixed-column--left){
  outline: var(--el-table-border);
  border: none !important;
}
:deep(.el-table-fixed-column--right){
  outline: var(--el-table-border);
  border: none !important;
}
:deep(.caret-wrapper){
  width: 0;
}
</style>